package com.gitee.faster.webdav.kernel.protocol.dispatcher;

import com.gitee.faster.webdav.common.constant.MethodEnum;
import com.gitee.faster.webdav.kernel.protocol.HttpExchange;
import com.gitee.faster.webdav.kernel.resource.Resource;
import com.gitee.faster.webdav.kernel.resource.ResourceRepository;
import lombok.extern.slf4j.Slf4j;
import org.smartboot.http.common.enums.HttpStatus;

/**
 * @author hongda.li
 */
@Slf4j
public class MethodDispatcherMkcol implements MethodDispatcher {
    @Override
    public MethodEnum supported() {
        return MethodEnum.MKCOL;
    }

    @Override
    public void dispatch(HttpExchange accessor) {
        // 当前目录
        Resource resource = accessor.getResource();
        ResourceRepository repository = accessor.getRepository();

        // 当前的父目录必须存在
        Resource parent = resource.getParent();
        if (parent != null && parent.exists()) {
            log.info("创建目录成功 : {}", resource.getName());
            repository.mkdir(resource);
            accessor.setHttpStatus(HttpStatus.CREATED);
        } else {
            log.warn("父级目录不存在 : {}", resource.getName());
            accessor.setHttpStatus(HttpStatus.FORBIDDEN);
        }
    }
}
